<script setup>
import {
  getCloudList,
  addCloudFile,
  delCloudFile,
  moveCloudFile,
  copyCloudFile
} from "@/api/myClooud";
import { useRouter, onBeforeRouteLeave } from "vue-router";
import { message } from "@/utils/message";
import { ref, onMounted, h, toRaw, onBeforeMount } from "vue";
import CopyandArrowFrom from "./components/Dialog/CopyandArrowFrom.vue";
import { ElMessageBox } from "element-plus";
import FolderRenameForm from "./components/Dialog/FolderRenameForm.vue";
import FileRenameForm from "./components/Dialog/FileRenameForm.vue";
import FoldersCard from "./components/FoldersCard.vue";
import FileCard from "./components/FileCard.vue";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import AddFill from "@iconify-icons/ri/file-add-fill";
import folder from "@/assets/svg/folder.svg";
import { addDialog, closeDialog } from "@/components/ReDialog";
defineOptions({
  name: "myCloud"
});

const svg = `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `;
const router = useRouter();
const foldersList = ref([]);
const fileList = ref([]);
const historyList = ref([]);
const dataLoading = ref(true);
const searchName = ref("");
const formRef = ref();
const onSearch = async data => {
  dataLoading.value = true; // 确保在请求开始时设置加载状态
  try {
    const params = {
      parentId:
        data?.id || historyList.value[historyList.value.length - 1]?.id || 0,
      searchName: searchName.value
    };
    const response = await getCloudList(params);
    const {
      myDirViewList,
      myDocumentViewList,
      historyList: historyData
    } = response.data;
    // 赋值
    foldersList.value = myDirViewList;
    fileList.value = myDocumentViewList;
    historyList.value = historyData;
  } catch (error) {
    message("获取数据失败", { type: "error" });
  } finally {
    dataLoading.value = false; // 确保在请求结束时重置加载状态
  }
};

onMounted(() => {
  onSearch();
});
onBeforeMount(() => {
  historyList.value = JSON.parse(localStorage.getItem("historyList")) || [];
});

const addFolder = type => {
  addDialog({
    title: "新建文件夹",
    props: {
      formInline: {
        name: "",
        width: "",
        height: "",
        canvasPicUrl: "",
        type,
        parentId: historyList.value[historyList.value.length - 1].id
      }
    },
    width: "30%",
    draggable: true,
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(FolderRenameForm),
    beforeSure: async (done, { options }) => {
      const data = {
        ...options.props.formInline,
        parentId: historyList.value[historyList.value.length - 1].id
      };
      try {
        await addCloudFile(data);
        message(`${data.name}添加成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        onSearch(); // 刷新表格数据
      } catch (error) {
        message(`添加失败`, {
          type: "error"
        });
      }
    }
  });
};
const addFile = type => {
  addDialog({
    title: "新建文件",
    props: {
      formInline: {
        name: "",
        width: "",
        height: "",
        canvasPicUrl: "",
        type,
        parentId: historyList.value[historyList.value.length - 1].id
      }
    },
    width: "30%",
    draggable: true,
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(FileRenameForm, { ref: formRef }),
    beforeSure: (done, { options }) => {
      const data = {
        ...options.props.formInline,
        parentId: historyList.value[historyList.value.length - 1].id
      };
      const FormRef = formRef.value.getRef();
      FormRef.validate(valid => {
        if (valid) {
          router.push({
            name: "tagGraph",
            query: {
              name: data.name,
              width: data.width,
              height: data.height,
              parentId: data.parentId
            }
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        } else {
          message(`请填写完整`, {
            type: "error"
          });
        }
      });
    }
  });
};
const handleClickRename = row => {
  let type = row.type;

  addDialog({
    title: "重命名",
    props: {
      formInline: {
        name: row?.name ?? "",
        id: row?.id ?? 0,
        width: row?.width ?? "",
        height: row?.height ?? "",
        canvasPicUrl: row?.canvasPicUrl ?? "",
        type,
        parentId: historyList.value[historyList.value.length - 1].id
      }
    },
    width: "30%",
    draggable: true,
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(type == "dir" ? FolderRenameForm : FileRenameForm),
    beforeSure: async (done, { options }) => {
      const data = {
        ...options.props.formInline,
        name: options.props.formInline.name,
        parentId: historyList.value[historyList.value.length - 1].id,
        type
      };
      try {
        await addCloudFile(data);
        message(`${data.name}重命名成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        onSearch(); // 刷新表格数据
      } catch (error) {
        message("重命名失败", {
          type: "error"
        });
      }
    }
  });
};
const handleClickOption = row => {
  addDialog({
    title: "复制或移动文件夹",
    props: {
      formInline: {
        folderList: foldersList,
        currentId: row?.id ?? "",
        targetId: ""
      }
    },
    footerButtons: [
      {
        label: "取消",
        text: true,
        bg: true,
        btnClick: ({ dialog: { options, index }, button }) => {
          closeDialog(options, index);
        }
      },
      {
        label: "移动",
        text: true,
        bg: true,
        type: "primary",
        btnClick: async ({ dialog: { options, index }, button }) => {
          const data = {
            currentDocId: options.props.formInline.currentId,
            targetDocId: options.props.formInline.targetId
          };
          try {
            await moveCloudFile(data);
            message(`操作成功`, {
              type: "success"
            });
            closeDialog(options, index);
            onSearch(); // 刷新表格数据
          } catch (error) {
            message("操作失败", {
              type: "error"
            });
          }
        }
      },
      {
        label: "复制",
        text: true,
        bg: true,
        type: "primary",
        btnClick: async ({ dialog: { options, index }, button }) => {
          const data = {
            currentDocId: options.props.formInline.currentId,
            targetDocId: options.props.formInline.targetId
          };
          try {
            await copyCloudFile(data);
            message(`操作成功`, {
              type: "success"
            });
            closeDialog(options, index);
            onSearch(); // 刷新表格数据
          } catch (error) {
            message("操作失败", {
              type: "error"
            });
          }
        }
      }
    ],
    width: "30%",
    draggable: true,
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(CopyandArrowFrom)
  });
};

const handleClickDelete = row => {
  ElMessageBox.confirm(
    `删除文件夹<strong style='color:var(--el-color-primary)'>${
      row.name
    }</strong>后,文件夹下的文件也将一并被移入回收站，是否删除？`,
    "系统提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      draggable: true
    }
  )
    .then(() => {
      delCloudFile({ docId: row.id })
        .then(() => {
          message(`删除${row.name}文件夹成功`, {
            type: "success"
          });
          onSearch(); // 刷新表格数据
        })
        .catch(() => {
          message(`删除${row.name}文件夹失败`, {
            type: "error"
          });
        });
    })
    .catch(e => {
      console.log(e.message);
    });
};
const handleClickDeleteFile = row => {
  ElMessageBox.confirm(
    `文件<strong style='color:var(--el-color-primary)'>${
      row.name
    }</strong>将被移入回收站,是否删除?`,
    "系统提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
      dangerouslyUseHTMLString: true,
      draggable: true
    }
  )
    .then(() => {
      delCloudFile({ docId: row.id })
        .then(() => {
          message(`删除${row.name}文件成功`, {
            type: "success"
          });
          onSearch(); // 刷新表格数据
        })
        .catch(() => {
          message(`删除${row.name}文件失败`, {
            type: "error"
          });
        });
    })
    .catch(e => {
      console.log(e.message);
    });
};

const handleGoTagGraph = row => {
  router.push({
    name: "tagGraph",
    query: { id: row.id, parentId: row.parentId }
  });
};
onBeforeRouteLeave((to, from, next) => {
  //将historyList存入localStorage
  localStorage.setItem("historyList", JSON.stringify(historyList.value));
  next();
});
</script>

<template>
  <div>
    <div class="w-full flex justify-between mb-9">
      <el-input
        v-model="searchName"
        style="width: 300px"
        placeholder="请输入文件/文件夹名称"
        clearable
        @change="onSearch"
      >
        <template #suffix>
          <el-icon class="el-input__icon">
            <IconifyIconOffline
              v-show="searchName.length === 0"
              icon="ri:search-line"
            />
          </el-icon>
        </template>
      </el-input>
      <div>
        <el-button :icon="useRenderIcon(folder)" @click="addFolder('dir')">
          新建文件夹
        </el-button>
        <el-button :icon="useRenderIcon(AddFill)" @click="addFile('file')">
          新建文件
        </el-button>
      </div>
    </div>
    <div
      v-loading="dataLoading"
      :element-loading-svg="svg"
      element-loading-svg-view-box="-10, -10, 50, 50"
    >
      <el-breadcrumb>
        <el-breadcrumb-item
          v-for="(item, index) in historyList"
          :key="index"
          style="color: #9aa5b8; cursor: pointer"
          @click="onSearch(item)"
          >{{ item.name }}</el-breadcrumb-item
        >
      </el-breadcrumb>

      <el-divider />
      <el-empty
        v-show="foldersList?.length == 0 && fileList?.length == 0"
        :description="`${searchName} 空空如野`"
      />
      <template v-if="foldersList?.length > 0">
        <p class="title">文件夹</p>
        <FoldersCard
          :folderList="foldersList"
          @handleClickRename="handleClickRename"
          @handleClickOption="handleClickOption"
          @handleClickDelete="handleClickDelete"
          @handleClickItem="onSearch"
        />
      </template>
      <template v-if="fileList?.length > 0">
        <p class="title">文件</p>
        <FileCard
          :fileList="fileList"
          @handleEditFile="handleClickRename"
          @handleClickOption="handleClickOption"
          @handleDelFile="handleClickDeleteFile"
          @clickGoDetil="handleGoTagGraph"
        />
      </template>
    </div>
  </div>
</template>
<style scoped lang="scss">
.el-divider--horizontal ::v-deep {
  margin: 12px 0;
}

.el-breadcrumb::v-deep {
  font-size: 15px;
}

.title {
  height: 20px;
  margin-top: -4px;
  margin-bottom: 8px;
  font-size: 12px;
  line-height: 20px;
  color: #9aa5b8;
}
</style>
